<template>
  <div ref="mapEl" />
</template>

<script>
/*
 *@description: 鼠标定位
 *@author: fxj
 *@date: 2021-10-08 18:18:57
*/
import { onMounted, reactive, toRefs, watch } from '@vue/composition-api'
import initMap from './initMap'
export default {
  props: {
    pt: {
      type: Array,
      require: true,
      default() {
        return []
      }
    }
  },
  setup(props, ctx) {
    const state = reactive({
      marker: null
    })
    const { mapEl, Bm } = initMap()

    watch(() => props.pt, updateCenter)

    onMounted(() => {
      const map = Bm.map
      drivingRoute()
      updateCenter(props.pt)

      map.addEventListener('click', function(e) {
        // alert('点击位置经纬度：' + e.latlng.lng + ',' + e.latlng.lat)
        createdMarker(e.point.lng, e.point.lat)
        ctx.emit('change', { lng: e.point.lng, lat: e.point.lat })
      })
    })

    function updateCenter(v) {
      const map = Bm.map
      const BMap = Bm.BMap
      var point = new BMap.Point(v[0], v[1])
      map.setCenter(point)
      createdMarker(v[0], v[1])
    }

    function createdMarker(lng, lat) {
      const map = Bm.map
      const BMap = Bm.BMap
      const point = new BMap.Point(lng, lat)
      state.marker && map.removeOverlay(state.marker)
      state.marker = null
      var marker = new BMap.Marker(point, {
        enableDragging: true
      })
      marker.addEventListener('dragend', function() {
        var nowPoint = marker.getPosition()
        ctx.emit('change', { lng: nowPoint.lng, lat: nowPoint.lat })
      })
      state.marker = marker
      map.addOverlay(marker)
    }

    function drivingRoute() {
      const map = Bm.map
      const BMap = Bm.BMap
      var p1 = new BMap.Point(104.188365, 30.627248)
      var p2 = new BMap.Point(105.427002, 29.389793)
      var driving = new BMap.DrivingRoute(map, {
        renderOptions: { map: map, autoViewport: true },
        onMarkersSet: function(routes) {
          for (var i = 0; i < routes.length; i++) {
            if (i == 0 || i == routes.length - 1) {
              map.removeOverlay(routes[i].marker)
            } else {
              map.removeOverlay(routes[i].Um)
            }
          }
        }
      })
      driving.search(p1, p2)
    }

    // 104.807684 30.0085205
    return {
      mapEl
    }
  }
}
</script>

<style>

</style>
